package org.mobilesynergies.tuneserver;


import iTunes.def.ClassFactory;
import iTunes.def.IITTrack;
import iTunes.def.IiTunes;
import iTunes.def.events._IiTunesEvents;

import org.mobilesynergies.epic.client.EpicClient;


import com4j.EventCookie;

/**
 * This demo application connects to iTunes and offers a remote interface to control iTunes.
 * The remote interface is controlled with any device running an EPIC client and offering Remote Human User Interfaces.
 * 
 * @author rautek
 *
 */
public class TuneStarter {

	private static String USERNAME = "andi";
	private static String PASSWORD = "andi";
	private static String SERVER = "blindeshendl.cg.tuwien.ac.at";

	private static TuneStarter mApplicationSingleton = new TuneStarter();

	private TuneStarter() {

	}

	private static EventCookie cookie = null;

	private IiTunes mITunes = null;

	private void init(){

		mITunes = ClassFactory.createiTunesApp();

		cookie = mITunes.advise(_IiTunesEvents.class, new _IiTunesEvents() {
			public void onDatabaseChangedEvent(Object deletedObjectIDs, Object changedObjectIDs) {
				System.out.println("Database changed:" + deletedObjectIDs + "," + changedObjectIDs);
			}

			public void onPlayerPlayEvent(Object iTrack) {
				System.out.println("Playing ");
				IITTrack track = mITunes.currentTrack();
				if(track==null) {
					System.out.println("Nothing is playing");
				} else {
					System.out.println("Now playing album: "+ track.album() + ", track name: "+track.name()+", by: "+track.artist()+", duration: "+track.duration());

				}
			}

			public void onPlayerStopEvent(Object iTrack) {
				System.out.println("Stopped ");
			}
		});

		
		
		EpicClient client = new EpicClient();
		try{
			if(client.establishConnection(SERVER)){
				client.authenticateUser(USERNAME, PASSWORD);
			}
			
			ChooseTrackCommand remoteCommandChooseTrack = new ChooseTrackCommand();
			client.announceRemoteCommand(remoteCommandChooseTrack);
			
		} catch (Exception e) {

		}
	}



	public static void main(String args[]) throws Exception {
		mApplicationSingleton.init();
		boolean bCanceled = false;
		
		while(!bCanceled) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				bCanceled = true;
			}
		}
		
		cookie.close();
		System.exit(0);
	}


	public static TuneStarter getApplicationInstance() {
		return mApplicationSingleton;
	}



	public IiTunes getITunesController() {
		return mITunes;
	}

}